<?php 
require_once("db.php");
date_default_timezone_set('America/Sao_Paulo');

if(isset($_GET['action']) && $_GET['module'] == 'add'){
	if(isset($_GET['module'])){
		$module == $_GET['module'];
		
		switch ($module) {
	    case "system":
	    	addSystem($_POST['name'],$_POST['description']);
	        break;
		case "supplement":
	    	addSystem($_POST['name'],$_POST['description'],$_POST['']);
	        break;
		default:
	    	echo "N&atilde;o existe o m&oacute;dulo que voc&ecirc; escolheu... p&aacute;ra de tentar injection.";
	        break;
		}
	}
}


/*****************
**** REGISTER ****
*****************/

function register($name, $user, $pass, $mail){
	
	$unique = "SELECT * FROM user WHERE UserName='$user' OR Email='$mail'";
	$query = mysql_query("$unique") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	
	$q_user = strtolower($query['user']);
	$q_mail = strtolower($query['mail']);
	$l_user = strtolower($user);
	$l_mail = strtolower($mail);


	if($q_mail == $l_mail){
		echo("E-mail j&aacute; utilizado.<br />");
	}
	if($q_user == $l_user){
		echo("Usu&aacute;rio j&aacute; existente.<br />");
	}
	if(($q_user != $l_user) and ($q_mail != $l_mail)){
		$q = "INSERT INTO user(name,userName,password,email,regDate) VALUES('$name','$user','$pass','$mail',CURDATE());";
		$query = mysql_query("$q") or die(mysql_error());
		return true;
	}
}

/*****************
****** LOGIN *****
*****************/

function login($user, $pass){
	$q = "SELECT * FROM user WHERE userName='$user'";
	$query = mysql_query("$q") or die(mysql_error());
	$numRows = mysql_num_rows($query);
	print_r($query = mysql_fetch_array($query, MYSQL_BOTH));
	
	$q_user = strtolower($query['username']);
	$l_user = strtolower($user);
	
	if($numRows == 1){
		if(($q_user == $l_user)&&($query['password'] == $pass)){
		$_SESSION['user'] = $query['userName'];
		}
		if(isset($_SESSION['user'])){
			return TRUE;
			}
	}else{
		echo("Login Nao Efetuado.");
		return FALSE;
	}
}

/*****************
***** LOGOUT *****
*****************/

function logout(){
	if(isset($_SESSION['user'])){
		unset($_SESSION['user']);
		return true;
	}else{
		echo("Erro ao Deslogar");
		return false;
	}
}

/**********************************
***** Fetch Full Result Array *****
***********************************/

function mysql_fetch_full_result_array($result)
{
    $table_result=array();
    $r=0;
    while($row = mysql_fetch_assoc($result)){
        $arr_row=array();
        $c=0;
        while ($c < mysql_num_fields($result)) {       
            $col = mysql_fetch_field($result, $c);   
            $arr_row[$col -> name] = $row[$col -> name];           
            $c++;
        }   
        $table_result[$r] = $arr_row;
        $r++;
    }   
    return $table_result;
}


/*****************
***** User *****
****************/

function editUser($id,$name,$email,$avatar){
	$q = "UPDATE user.name,user.email,user.avatar SET user.name=$name,user.email=$email,user.avatar=$avatar WHERE user.idUser=$id;";
	$query = mysql_query("$q") or die(mysql_error());
	return true;	
}

function getUserId($user){//Retorna o ID do usuário
	$q = "SELECT idUser FROM user WHERE UserName='$user'";
	$query = mysql_query("$q") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$ret = $query['idUser'];
	return $ret;
}

function getUserName($id){//Retorna o nome do usuário
	$q = "SELECT name FROM user WHERE idUser='$id'";
	$query = mysql_query("$q") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$ret = $query['name'];
	return $ret;
}

function getUserAvatar($id){//Retorna o nome do usuário
	$q = "SELECT avatar FROM user WHERE idUser='$id'";
	$query = mysql_query("$q") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$ret = $query['avatar'];
	return $ret;
}

function getUserUserName($id){//Retorna o nome do usuário
	$q = "SELECT username FROM user WHERE idUser='$id'";
	$query = mysql_query("$q") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$ret = $query['username'];
	return $ret;
}

function getUserEmail($id){//Retorna o E-Mail do usuário
	$q = "SELECT email FROM user WHERE idUser='$id'";
	$query = mysql_query("$q") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$ret = $query['email'];	
	return $ret;
}

function isAdmin($id){// Verifica se o usuário é administrador
	$q = "SELECT admin FROM user WHERE idUser='$id'";
	$query = mysql_query("$q") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$ret = $query['admin'];
	if($ret==1){return TRUE;}else{return FALSE;}
}

function isLogged($user){//Verifica se o usu�rio est� logado.
	$q = "SELECT username FROM user WHERE username='$user'";
	$query = mysql_query("$q") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$userLower = strtolower($query['username']);
	$userSession = strtolower($user);
	if($userLower==$userSession){return TRUE;}else{return FALSE;}
}

function editPerfil($name,$avatar,$email,$id){
	$q = "UPDATE user SET Name='$name',Email='$email',avatar='$avatar' WHERE idUser='$id';";
	$query = mysql_query("$q") or die(mysql_error());
	header("location: /home/p/home");
}

/*****************
***** CHAR *****
****************/

function getCharacters($id){//Recebe listagem de Personagens do usuário.
$query="SELECT 
			character.idCharacter, 
			character.name AS charName,
			user.name AS userName,
			status.name AS status,
			chronicle.name AS chronicle,
			supplement.name AS supplement,
			supplement.description AS supDesc
		FROM 
		`character`,user,status,chronicle,supplement 
		WHERE 
				user.idUser 			= character.idUser
			AND status.idStatus 		= character.idStatus 
			AND chronicle.idChronicle 	= character.idChronicle
			AND chronicle.idSupplement 	= supplement.idSupplement
			AND user.idUser 			='$id'
		ORDER BY status
		LIMIT 0 , 30";
$result = mysql_query($query) or die(mysql_error());
$numRows = mysql_num_rows($result);
if($numRows > 0){
	$cont = 0; 
	$arr_table_result=mysql_fetch_full_result_array($result);
	echo"<table>";
	echo"<tr><th>Status</th><th>Nome</th><th>Cr&ocirc;nica</th><th>Suplemento</th><th>A&ccedil;&otilde;es</th></tr>";
	while($cont<$numRows){
			$charName 		= 	$arr_table_result[$cont]['charName'];
			$status			=	$arr_table_result[$cont]['status'];
			$chronicle		=	$arr_table_result[$cont]['chronicle'];
			$supplement		=	$arr_table_result[$cont]['supplement'];
			$supDesc		=	$arr_table_result[$cont]['supDesc'];
			echo("<tr class=");
			if(($cont % 2)!=0){echo("rowimpar");}else{echo("rowpar");}
			echo("><td>$status</td><td>$charName</td><td>$chronicle</td><td><dfn title='$supDesc'>$supplement</dfn></td><td><a href='#'><img class='icon' alt='Visualizar' title='Ver' src='/img/icons/page_go.png' /></a>&nbsp;<a href='#'><img class='icon' alt='Edit' title='Editar' src='/img/icons/page_edit.png' /></a>&nbsp;<a href='#'><img alt='Delete' class='icon' title='Deletar'  src='/img/icons/cross.png' /></a></td></tr>");
		$cont++;
		}
	echo"</table>";
}else{
	echo"Voc&ecirc; n&atilde;o possui nenhum personagem cadastrado.";
}
}

/*****************
***** System *****
*****************/

function addSystem($nome,$descricao){//Recebe listagem de Personagens do usuário.
	$unique = "SELECT * FROM system WHERE name='$nome'";
	$query = mysql_query("$unique") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	
	$q_name = strtolower($query['name']);
	$l_name = strtolower($nome);
	$now = date('Y/m/d');
	$q = "INSERT INTO system(name,description,dtCreation) VALUES('$nome','$descricao','$now')";

	if($q_name == $l_name){
		echo("j&aacute; existe um sistema com este nome, favor escolher outro.<br />");
		return false;
	}else{
		$query = mysql_query("$q") or die(mysql_error());
		header("location: /home/p/home");
	}
}

/************************
***** BUILD SELECT ******
************************/

function buildSelectSystem(){
	$query = "SELECT system.name, system.idSystem FROM system";
	$result = mysql_query($query) or die(mysql_error());
	$numRows = mysql_num_rows($result);
	$cont = 0;
	$arr_table_result=mysql_fetch_full_result_array($result);
	if($numRows > 0){
		echo"<select name='idSystem'>";
		while($cont<$numRows){
			$system 		= 	$arr_table_result[$cont]['name'];
			$id 			= 	$arr_table_result[$cont]['idSystem'];
			echo"<option value='$id'>$system</option>";
		$cont++;
		}
		echo"</select>";
	}else{echo "n&atilde;o existem systemas cadastrados.";}
}

function buildSelectSupplement(){
	$query = "SELECT supplement.name, supplement.idSupplement FROM supplement";
	$result = mysql_query($query) or die(mysql_error());
	$numRows = mysql_num_rows($result);
	$cont = 0;
	$arr_table_result=mysql_fetch_full_result_array($result);
	if($numRows > 0){
		echo"<select name='idSupplement'>";
		while($cont<$numRows){
			$supplement 		= 	$arr_table_result[$cont]['name'];
			$idSup 				= 	$arr_table_result[$cont]['idSupplement'];
			echo"<option value='$idSup'>$supplement</option>";
		$cont++;
		}
		echo"</select>";
	}else{echo "n&atilde;o existem suplementos cadastrados.";}
}


/*********************
***** Supplement *****
*********************/

function addSupplement($name, $description, $idSystem){
	$unique = "SELECT * FROM supplement WHERE name='$name'";
	$query = mysql_query("$unique") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$q = "	INSERT INTO `rpgcom`.`supplement` (`idSupplement`, `name`, `description`, `idSystem`) 
			VALUES (NULL, '$name', '$description', '$idSystem');";
	
	$q_name = strtolower($query['name']);
	$l_name = strtolower($name);

	if($q_name == $l_name){
		echo("j&aacute; existe um suplemento com este nome, favor escolher outro.<br />");
		return false;
	}else{
		$query = mysql_query("$q") or die(mysql_error());
		header("location: /home/p/home");
	}
}

/*********************
***** Chronicle ******
*********************/

function addChronicle($name,$description, $idStoryteller, $idSupplement, $dtIni, $dtEnd){
	$unique = "SELECT * FROM chronicle WHERE name='$name'";
	$query = mysql_query("$unique") or die(mysql_error());
	$query = mysql_fetch_array($query, MYSQL_BOTH);
	$q = "	INSERT INTO `rpgcom`.`supplement` (`idChronicle`, `name`, `description`, `idStoryteller`, `idSupplement`, `dtIni`, `dtEnd`) 
			VALUES (NULL, '$name', '$description', '$idStoryteller', '$idSupplement', '$dtIni', '$dtEnd');";
	
	$q_name = strtolower($query['name']);
	$l_name = strtolower($name);

	if($q_name == $l_name){
		echo("j&aacute; existe um suplemento com este nome, favor escolher outro.<br />");
		return false;
	}else{
		$query = mysql_query("$q") or die(mysql_error());
		header("location: /adm/supplement/add");
	}
}

?>